<template>
    <div>
        <el-dialog v-model="props.visible" title="物料选择" width="70%" @close="handleCancel">
            <el-form :model="queryParams" ref="queryRef" :inline="true">
                <el-row>
                    <el-form-item label="物料编码">
                        <el-input v-model="queryParams.code" placeholder="请输入物料编码" clearable style="width: 200px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="物料名称">
                        <el-input v-model="queryParams.name" placeholder="请输入物料名称" clearable style="width: 200px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
            <el-row :gutter="10">
                <el-col :span="5">
                    <el-tree highlight-current :default-expand-all="true" style="margin-top: 5%;" :data="treeDate" :props="defaultProps"
                        @node-click="handleNodeClick" />
                </el-col>
                <el-col :span="19">
                    <el-button style="margin-bottom: 5px;" type="primary" plain @click="handleSubmit"
                        :disabled="multiple">确认</el-button>
                    <el-table v-loading="loading" :data="materielList" row-key="id" stripe border style="cursor: pointer;"
                        @selection-change="handleCellClick">
                        <el-table-column type="selection" width="55" align="center" />
                        <!-- <el-table-column label="序号" width="80" type="index" align="center" /> -->
                        <el-table-column label="物料编号" width="150" align="center" prop="code">
                        </el-table-column>
                        <el-table-column label="物料名称" align="center" prop="name"  width="100"/>
                        <el-table-column label="物料全称" align="center" prop="fullName"  width="100"/>
                        <el-table-column label="物料品牌" align="center" prop="brand">
                            <template #default="scope">
                                <dict-tag :options="mes_material_brand" :value="scope.row.brand" />
                            </template>
                        </el-table-column>
                        <el-table-column label="实时单价" align="center" prop="realtimePrice" />
                        <el-table-column label="库存数量" align="center" prop="quantity" />
                        <el-table-column label="计量单位" align="center" prop="unit">
                            <template #default="scope">
                                <dict-tag :options="mes_material_unit" :value="scope.row.unit" />
                            </template>
                        </el-table-column>
                        <el-table-column label="所属分类" align="center" prop="belongClass" />
                        <el-table-column label="自有编码" align="center" prop="originalCode" />
                        <el-table-column label="规格型号" align="center" prop="specs" />
                        <el-table-column label="采购专员编码" align="center" prop="buyerCode" />
                        <el-table-column label="采购专员" align="center" prop="buyerName" />
                        <el-table-column label="定量" align="center" prop="weight" />
                        <el-table-column label="长度" align="center" prop="longWide" />
                        <el-table-column label="宽度" align="center" prop="wide" />
                        <el-table-column label="高度" align="center" prop="height" />
           

                        <el-table-column label="加权单价" align="center" prop="authorityPrice" />
                        <el-table-column label="库存金额" align="center" prop="stockPrice" />
                        <el-table-column label="安全库存" align="center" prop="safetyStock" />
                        <el-table-column label="最低库存" align="center" prop="minStock" />
                        <el-table-column label="最高库存" align="center" prop="maxStock" />
                        <el-table-column label="最初库存" align="center" prop="originalStock" />
                        <el-table-column label="所属仓库" align="center" prop="store" />
                    </el-table>
                    <div class="footer">
                        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                            v-model:limit="queryParams.pageSize" @pagination="getList" />
                    </div>
                </el-col>
            </el-row>

        </el-dialog>
    </div>
</template>

<script setup>
const emit = defineEmits(['changeUpdate'])
import { listMaterialclass, listMaterial } from '@/api/basicInfo/accessory.js'

const { proxy } = getCurrentInstance();
const { mes_material_brand, mes_material_unit } = proxy.useDict('mes_material_brand', 'mes_material_unit');

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
})
watch(() => props.visible, (val) => {
    if (val) {
        handleQuery()
    }
})
const multiple = ref(true)
const selectRow = ref([])
const materielList = ref([])
const treeDate = ref([])
const loading = ref(false)
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    status: 0,
    code: undefined,
    name: undefined,
    id: undefined

})
const defaultProps = {
    children: 'children',
    label: node => `${node.name} - ${node.code}`
}
const total = ref(0)
// 选中当前行
const handleCellClick = (row) => {
    // proxy.$modal.confirm('是否确认选择「' + row.name + '」').then(function () {
    //     emit('changeUpdate', row)
    // }).catch(() => { });
    selectRow.value = row
    multiple.value = !row.length
}
const handleSubmit =()=>{
    console.log('selectRow.value',selectRow.value)
       emit('changeUpdate', selectRow.value)
}

const handleCancel = () => {
    proxy.resetForm("queryRef");
    queryParams.code = undefined
    queryParams.name = undefined
    queryParams.id = undefined
    emit('cancel')
}
const getList = async () => {
    loading.value = true
    const res = await listMaterial(queryParams.value)
    loading.value = false
    materielList.value = res.rows
    total.value = res.total
}
const handleNodeClick = (data) => {
    queryParams.value.id = data.id
    getList()

}
const treeToMultiArray = (treeData) => {
    const result = [];
    const map = new Map(); // 使用 Map 代替普通对象

    treeData.forEach((item) => {
        map.set(item.id, item);
        item.children = [];
    });
    treeData.forEach((item) => {
        if (item.pid === 0) {
            // 如果 pid 为 0，说明是根节点
            result.push(item);
        } else {
            // 如果 pid 不为 0，将当前节点放入对应的父节点的 children 中
            const parent = map.get(item.pid);
            if (parent) {
                parent.children.push(item);
            }
        }
    });
    return result;
};
const CodeTree = async () => {
    try {
        const response = await listMaterialclass();
        console.log('response', response);
        treeDate.value = treeToMultiArray(response.data)
    } catch (error) {
        console.error('Error', error);
    }
};
// 搜索
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
    proxy.resetForm("queryRef");
    queryParams.value.code = undefined
    queryParams.value.name = undefined
    queryParams.value.id = undefined
    handleQuery();
};
getList()
CodeTree()
</script>

<style lang="scss" scoped></style>